package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.RepairCourseOutStudent;
import com.xmy.cultivate.enums.StatusSchedulingEnum;
import com.xmy.cultivate.service.ICourseSchedulingDetailService;
import com.xmy.cultivate.service.IRecordCourseService;
import com.xmy.cultivate.service.IRepairCourseService;
import com.xmy.cultivate.service.IStudentService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 排课详情 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-08-01
 */
@RestController
@RequestMapping("/api/courseScheduling")
@Scope("prototype")
public class CourseSchedulingDetailController extends BaseController {


    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IRepairCourseService iRepairCourseService;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    /**
     * 日程表
     *
     * @param reMap
     * @return
     */
    @GetMapping("/calendarList")
    public Result calendarList(@RequestParam Map<String, String> reMap,
                               @RequestParam(name = "yearPart", required = false) String yearPart,
                               @RequestParam(name = "status", required = false) String status,
                               @RequestParam(name = "lessonType", required = false) String lessonType) {

        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));
        IPage<CourseSchedulingDetail> iPage = new Page<>(pageNum, pageSize);

        String startDate = reMap.get("startDate");
        String endDate = reMap.get("endDate");
        String gradeId = reMap.get("gradeId");
        String teacherId = reMap.get("teacherId");
        String keyType = reMap.get("keyType");
        String keyWord = reMap.get("keyWord");
        String quarterNum = reMap.get("quarterNum");
        String subjectId = reMap.get("subjectId");
        String yearClassId = reMap.get("yearClassId");


        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            courseSchedulingDetailQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.le("school_date", endDate);
        }
        if (StringUtils.isNotBlank(keyType) && StringUtils.isNotBlank(keyWord)) {
            //搜索关键词类型：1班级名称，2教师名称，3助教名称，4教室名称
            if (keyType.equals("1")) {
                courseSchedulingDetailQueryWrapper.like("grade_name", keyWord);
            } else if (keyType.equals("2")) {
                courseSchedulingDetailQueryWrapper.like("teacher_name", keyWord);
            } else if (keyType.equals("3")) {
                courseSchedulingDetailQueryWrapper.like("assistant_name", keyWord);
            } else if (keyType.equals("4")) {
                courseSchedulingDetailQueryWrapper.like("class_romm_name", keyWord);
            }
        }

        String schoolId = reMap.get("schoolId");
        if (StringUtils.isNotBlank(schoolId)) {
            courseSchedulingDetailQueryWrapper.eq("school_id", schoolId);
        } else {
            courseSchedulingDetailQueryWrapper.in("school_id", this.baseSchoolIdList);
        }
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(subjectId), "subjects_id", subjectId);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);

        if (this.sourseLeve.equals(2)) {
            courseSchedulingDetailQueryWrapper.eq("teacher_id", this.adminId);
        }

        courseSchedulingDetailQueryWrapper.eq("deleted", 0);
        courseSchedulingDetailQueryWrapper.orderByAsc("start_date_time","id");
        iCourseSchedulingDetailService.calendarList(iPage, courseSchedulingDetailQueryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @GetMapping("/outStudentList")
    public Result outStudentList(@RequestParam(value = "id") Long id) {

        if (id == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }

        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.eq("out_scheduling_detail_id", id);
        List<RepairCourse> repairCourseList = iRepairCourseService.list(repairCourseQueryWrapper);

        List<RepairCourseOutStudent> repairCourseOutStudents = new ArrayList<>();
        for (RepairCourse repairCourse : repairCourseList) {
            RepairCourseOutStudent repairCourseOutStudent = new RepairCourseOutStudent();
            BeanUtils.copyProperties(repairCourse, repairCourseOutStudent);
            Student student = iStudentService.getById(repairCourse.getStudentId());
            if (student != null) {
                repairCourseOutStudent.setStudentName(student.getName());
            }

            repairCourseOutStudents.add(repairCourseOutStudent);
        }
        return new Result(Code.OK, new PageResult(repairCourseOutStudents, (long) repairCourseOutStudents.size(), 1L));
    }

    /**
     * 查找冲突排课日程
     *
     * @param reMap
     * @return
     */
    @GetMapping("/getFindClash")
    public Result getFindClash(@RequestParam Map reMap) {

        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.between("school_date", startDate, endDate);
        }
        courseSchedulingDetailQueryWrapper.gt("count", 1);

        if (this.sourseLeve.equals(2)) {
            courseSchedulingDetailQueryWrapper.eq("teacher_id", this.adminId);
        }

        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.getFindClash(courseSchedulingDetailQueryWrapper);

        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }

    /**
     * 获取学生列表
     *
     * @return
     */
    @GetMapping("/getStudentList/{id}")
    public Result getStudentList(@PathVariable(value = "id") String id) {
        return new Result(Code.OK);
    }

    /**
     * 获取班级的排课信息
     *
     * @param gradeId
     * @return
     */
    @GetMapping("/getSchedulingForGradeId/{gradeId}")
    public Result getSchedulingForGradeId(@PathVariable(value = "gradeId") Long gradeId) {
        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("grade_id", gradeId);
        courseSchedulingDetailQueryWrapper.orderByAsc("lesson_num");
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.list(courseSchedulingDetailQueryWrapper);
        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }

    @PostMapping("/stopScheduling")
    public Result stopScheduling(@RequestBody List<String> idList) {
        String errorMsg = "";
        Integer num = 0;
        for (String id:idList) {
            CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(id);
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("scheduling_detail_id",courseSchedulingDetail.getId());
            Long count = iRecordCourseService.count(recordCourseQueryWrapper);
            if (count>0){
                errorMsg += courseSchedulingDetail.getGradeName()+"已有学生签到，操作失败";
            }else {
                if (courseSchedulingDetail.getStatus().equals(StatusSchedulingEnum.NO)) {
                    CourseSchedulingDetail courseSchedulingDetailNew = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());
                    if (courseSchedulingDetailNew != null) {
                        courseSchedulingDetailNew.setStatus(StatusSchedulingEnum.STOP);
                        iCourseSchedulingDetailService.updateById(courseSchedulingDetailNew);
                        num++;
                    }
                }else {
                    errorMsg += courseSchedulingDetail.getGradeName()+"状态不为“未记录”，操作失败";
                }
            }
        }
        String rs = "成功"+num+"条";
        if (StringUtils.isNotBlank(errorMsg)){
            rs += "；"+errorMsg;
        }
        return new Result(Code.OK, "", rs);
    }

    @PostMapping("/recoverScheduling")
    public Result recoverScheduling(@RequestBody List<String> idList) {
        String errorMsg = "";
        Integer num = 0;
        for (String id:idList) {
            CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(id);
            if (courseSchedulingDetail.getStatus().equals(StatusSchedulingEnum.STOP)) {
                CourseSchedulingDetail courseSchedulingDetailNew = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());
                if (courseSchedulingDetailNew != null) {
                    courseSchedulingDetailNew.setStatus(StatusSchedulingEnum.NO);
                    iCourseSchedulingDetailService.updateById(courseSchedulingDetailNew);
                    num++;
                }
            }else {
                errorMsg += courseSchedulingDetail.getGradeName()+"状态不为“暂停”，操作失败";
            }
        }
        String rs = "成功"+num+"条";
        if (StringUtils.isNotBlank(errorMsg)){
            rs += "；"+errorMsg;
        }
        return new Result(Code.OK, "", rs);
    }


    /**
     * 更新日期
     * @return
     */
    @PostMapping("/updateDateTime")
    public Result updateDateTime(@RequestBody CourseSchedulingDetail courseSchedulingDetailParam){
        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("school_date", courseSchedulingDetailParam.getSchoolDate());
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.list(courseSchedulingDetailQueryWrapper);

        Integer i = 0;
        for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
            String startDateTime = courseSchedulingDetail.getSchoolDate() + "T" + courseSchedulingDetail.getTimeStart() + ":00";
            String endDateTime = courseSchedulingDetail.getSchoolDate() + "T" + courseSchedulingDetail.getTimeEnd() + ":00";
            courseSchedulingDetail.setStartDateTime(LocalDateTime.parse(startDateTime));
            courseSchedulingDetail.setEndDateTime(LocalDateTime.parse(endDateTime));
            iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
            i++;
        }

        return new Result(Code.OK, "调整了："+i+"条数据", "");
    }

}
